"""Dogtag certificate management."""

import typing
from typing import cast
from urllib import parse

import requests

from . import secrets
from . import token


def _hv_auth_post(
    meta: dict[str, typing.Any],
    path: str,
    **kwargs: typing.Any,
) -> requests.Response:
    url = parse.urljoin(meta['vault_addr'], f'v1/auth/approle/role/{meta["role_id"]}/{path}')
    return secrets.SESSION.post(url, headers={'X-Vault-Token': secrets.vault_token()}, **kwargs)


@token.register_token('hv_secret_id_accessor')
class HvSecretIdAccessor(token.Token):
    """HashiCorp Vault secret IDs."""

    clean_active_versions = 1

    def _create_token(self, token_version: str, meta: dict[str, typing.Any]) -> str:
        """Create HashiCorp Vault secret IDs."""
        secret_data = _hv_auth_post(meta, 'secret-id').json()['data']
        meta['secret_id_accessor'] = secret_data['secret_id_accessor']

        accessor_data = _hv_auth_post(meta, 'secret-id-accessor/lookup', json={
            'secret_id_accessor': meta['secret_id_accessor'],
        }).json()['data']
        meta['created_at'] = accessor_data['creation_time']

        return cast(str, secret_data['secret_id'])

    def _destroy_token(self, token_version: str, meta: dict[str, typing.Any]) -> None:
        """Destroy a token version."""
        _hv_auth_post(meta, 'secret-id-accessor/destroy', json={
            'secret_id_accessor': meta['secret_id_accessor'],
        })

    def _validate_token(self, token_version: str, meta: dict[str, typing.Any]) -> None:
        """Validate a token version."""
        token_secret = secrets.secret(self.full_token_name(token_version))
        secrets.SESSION.post(parse.urljoin(meta['vault_addr'], 'v1/auth/approle/login'), json={
            'role_id': meta['role_id'],
            'secret_id': token_secret,
        })
